
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View,Image,
  Dimensions,TouchableOpacity,TextInput,KeyboardAvoidingView,ScrollView
} from 'react-native';
import KeyboardAvoid from 'react-native-keyboard-avoid';
import TopBar from '../../bar/TopBar'
import BASEURL from '../../api/api'
import Loading from '../../common/Loading'
import Toast, {DURATION} from 'react-native-easy-toast'
import Picker from 'react-native-picker';
import {createDateData,getCurrentDate} from '../../common/common'
import {isIphoneX} from '../../common/Utils'
import DeviceStorage from '../../common/DeviceStorage'
const dismissKeyboard = require('dismissKeyboard');
var {height, width} = Dimensions.get('window');
export default class ApplyAdd extends Component {
  static navigationOptions = ({ navigation }) =>{
    return{
      headerTitle:<TopBar title='新增申请' navigation = {navigation}/>,
      headerLeft:null,
    }
  };
  constructor(props){
    super(props);
    this.state = ({
      apply:{},
      loading:true,
      onFocus:false,
      dateData:[],
      applyStartTime:getCurrentDate(),
      startTimeTitle:'请选择开始时间',
      endTimeTitle:'请选择结束时间',
      applyEndTime:getCurrentDate(),
      empName:'请选择电站',
      powerStationPosition:'',
      applyPerson:'',
      applyPhone:'',
      applyContent:'',
      applyFor:'请选择申请原因',
      applyForList:['水量过小','检修','水毁事故','其他'],
      timeType:0,
      areaCode:'',
      empList:[],
      selEmp:{},
      isFinish:false,
      contentOffset:3,
    })
    //console.log(this.props)
  }
  componentWillMount(){
    //this.fetchData();
    DeviceStorage.get('areaCode').then((areaCode)=>{
      if(areaCode){
        this.setState({
          areaCode:areaCode
        })
      } 
    })
  }
  componentDidMount(){
    setTimeout(()=>{
      this._fetchStationInfo()
    },10)
    this.setState({
      dateData:createDateData(),
    })
    setTimeout(()=>{
      if(this.scrollView){
        this.scrollView.scrollTo({x: 0, y: 3, animated: false})
      }
      
    },50)
  }
  //获取待选择电站数据
  _fetchStationInfo(){
    fetch(BASEURL+'getEmpListTwo?areaCode='+this.state.areaCode)
    .then(res=>res.json())
    .then(response=>{
      console.log('response',response)
      if(response.falg){
        this.setState({
          empList:response.empList,
          loading:false,
          isFinish:true
        })
      } else {
        this.setState({
          loading:false,
        })
      }
    })
  }
  //组装选择电站数据
  _createEmpSelectInfo(){
    var data = []
    this.state.empList.forEach((item,index)=>{
      data.push(item.hy_name)
    })
    return data
  }
  //点击选择
  _onSelect(type){
    if(type == 'powerStationName'){ //选电站
      this._showStationPicker()
    }else if(type == 'applyStartTime'){
      this.setState({
        timeType:0,
      })
      this._openDateSel()
    } else if(type == 'applyEndTime'){
      this.setState({
        timeType:1,
      })
      this._openDateSel()
    } else if(type == 'applyFor'){ //申请原因
      this._showApplyForPicker()
    }
  }
  //显示申请原因窗口
  _showApplyForPicker(){
    var applyFor = this.state.applyFor
    //console.log(applyFor)
    //console.log(applyFor=='请选择申请原因')
    Picker.init({
      pickerTitleText:'申请原因选择',
      pickerCancelBtnText:'取消',
      pickerConfirmBtnText:'确定',
      selectedValue:[this.state.applyFor],
      pickerBg:[255,255,255,1],
      pickerData: this.state.applyForList,
      pickerFontColor: [33, 33 ,33, 1],
      onPickerConfirm: (pickedValue, pickedIndex) => {
          //console.log('选择的电站是:', pickedValue, pickedIndex);
          this.setState({
            applyFor:pickedValue
          })
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
      },
      onPickerSelect: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
      }
    });
    Picker.show();
  }
  //显示电站选择窗口
  _showStationPicker(){
    if(!this.state.isFinish){
      this.refs.toast.show("电站数据加载中...")
      return
    }
    var empName = this.state.empName
    Picker.init({
      pickerTitleText:'电站选择',
      pickerCancelBtnText:'取消',
      pickerConfirmBtnText:'确定',
      selectedValue:[empName=='请选择电站名称'?this.state.empList[0].hy_name:empName],
      pickerBg:[255,255,255,1],
      pickerData: this._createEmpSelectInfo(),
      pickerFontColor: [33, 33 ,33, 1],
      onPickerConfirm: (pickedValue, pickedIndex) => {
          console.log('选择的电站是:', pickedValue, pickedIndex);
          this.setState({
            selEmp:this.state.empList[pickedIndex],
            empName:this.state.empList[pickedIndex].hy_name
          })
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
      },
      onPickerSelect: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
      }
    });
    Picker.show();
  }
  _select(val){
    console.log('val',val)
  }
  _openDateSel(){
    setTimeout(()=>{
      this._showDatePicker()
    },10)
  }
  //打开日期选择
  _showDatePicker() {
    var year = ''
    var month = ''
    var day = ''
    var currStr 
    var dateStr = ''
    if(this.state.timeType==0){
      dateStr = this.state.applyStartTime
    } else if(this.state.timeType==1){
      dateStr = this.state.applyEndTime
    } 
    //console.log('dateStr',dateStr)
    year = dateStr.substring(0,4)
    month = parseInt(dateStr.substring(5,7))
    day = parseInt(dateStr.substring(8,10))
    Picker.init({
      pickerTitleText:'时间选择',
      pickerCancelBtnText:'取消',
      pickerConfirmBtnText:'确定',
      selectedValue:[year+'年',month+'月',day+'日'],
      pickerBg:[255,255,255,1],
      pickerData: this.state.dateData,
      pickerFontColor: [33, 33 ,33, 1],
      onPickerConfirm: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
          var year = pickedValue[0].substring(0,pickedValue[0].length-1)
          var month = pickedValue[1].substring(0,pickedValue[1].length-1)
          month = month.padStart(2,'0')
          var day = pickedValue[2].substring(0,pickedValue[2].length-1)
          day = day.padStart(2,'0')
          let str = year+'-'+month+'-'+day
          //console.log('str',str)
          //console.log('type',this.state.timeType)
          if(this.state.timeType==0){
            this.setState({
              applyStartTime:str,
              startTimeTitle:str,
            })
          } else if(this.state.timeType==1){
            this.setState({
              applyEndTiem:str,
              endTimeTitle:str,
            })
          }
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
      },
      onPickerSelect: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
      }
    });
    Picker.show();
  }
  _applyContent(val){
    this.setState({
      onFocus:false
    })
    this.refs.toast.show(val)
  }
  _onchange(val,type){
    if(type == 'powerStationPosition'){
      this.setState({
        powerStationPosition:val
      })
    } else if(type == 'applyPerson'){
      this.setState({
        applyPerson:val,
      })
    } else if(type == 'applyPhone'){
      this.setState({
        applyPhone:val,
      })
    }
  }
  _applyContent(val){
    this.setState({applyContent:val})
  }
  _submit(){
    dismissKeyboard()//收起键盘
    //console.log('refs',this.refs)
    let selEmp = this.state.selEmp
    let powerStationPosition = this.state.powerStationPosition
    let startTimeTitle = this.state.startTimeTitle
    let endTimeTitle = this.state.endTimeTitle
    let applyPerson = this.state.applyPerson
    let applyPhone = this.state.applyPhone
    let applyFor = this.state.applyFor
    let applyContent = this.state.applyContent
    var isPhone = /^([0-9]{3,4}-)?[0-9]{7,8}$/;//座机
    var isMob= /^0?1[3|4|5|7|8|9][0-9]\d{8}$/;// 手机号码
    if(!selEmp.hy_id){
      //this.refs.toast.show('请选择电站')
      this.refs.toast.show('请选择电站')
      return
    } else if(!powerStationPosition){
      this.refs.toast.show('请填写电站位置')
      return
    } else if(startTimeTitle == '请选择开始时间'){
      this.refs.toast.show('请选择开始时间')
      return
    } else if(endTimeTitle == '请选择结束时间'){
      this.refs.toast.show('请选择结束时间')
      return
    } else if(startTimeTitle > endTimeTitle){
      this.refs.toast.show('开始时间不能大于结束时间')
      return
    }else if(!applyPerson){
      this.refs.toast.show('请填写申请人')
      return
    } else if(!applyPhone){
      this.refs.toast.show('请填写联系方式')
      return
    } else if(!isMob.test(applyPhone)&& !isPhone.test(applyPhone)){
      this.refs.toast.show('联系方式格式不正确')
      return
    }else if(applyFor == '请选择申请原因'){
      this.refs.toast.show('请选择申请原因')
      return
    } else if(!applyContent){
      this.refs.toast.show('请填写申请内容')
      return
    } else {
      //this.refs.toast.show('ok',2500)
      fetch(BASEURL+'saveApply?hy_id='+selEmp.hy_id+'&hy_code='+selEmp.hy_code+
        '&hy_name='+selEmp.hy_name+'&hy_location='+powerStationPosition+
        '&start_time='+startTimeTitle+'&end_time='+endTimeTitle+'&applicant='+applyPerson+
        '&application='+applyFor+'&content='+applyContent+'&telephone='+applyPhone)
      .then(res=>res.json())
      .then(response=>{
        //console.log('save res=',response)
        if(response.falg){
          this.refs.toast.show('提交成功')
          setTimeout(()=>{
            this.props.navigation.push('applyList')
          },2000)
        } else {
          this.refs.toast.show('提交失败')
        }
      })
    }
  }
  _saveToServer(){

  }
  _onFocus () {
    KeyboardAvoid.checkNeedScroll({
        nodeRef: this.contentInput,         //TextInput ref
        scrollNodeRef: this.scrollView,     //ScrollView ref
        contentOffset: this.contentOffset   //ScrollView scrollOffset.y
    }, 'scroll', 0);
  }
  render(){
    //<KeyboardAvoidingView  behavior="position" enabled   
     //         contentContainerStyle={{backgroundColor:'white'}} keyboardVerticalOffset={-50}>
    return(
      <View style={styles.container}>
      <ScrollView  style={{flex:1}} 
        ref={(ref) => this.scrollView = ref}
        scrollEventThrottle={2}
         onScroll={(event) => {this.contentOffset = event.nativeEvent.contentOffset.y}}
        >
          
          <View style={{backgroundColor:'white'}}>
            <View style={{height:10,backgroundColor:'#f0f0f0'}}></View>
            <Select title='电站名称' subTitle={this.state.empName} press={()=>{this._onSelect('powerStationName')}}/>
            <Input title='电站位置' placeholder='请填写电站位置' change={(val)=>{this._onchange(val,'powerStationPosition')}}/>
            <Select title='申请开始时间' subTitle={this.state.startTimeTitle} rightImg={true} 
              press={()=>{this._onSelect('applyStartTime')}} />
            <Select title='申请结束时间' subTitle={this.state.endTimeTitle} rightImg={true}  
              press={()=>{this._onSelect('applyEndTime')}} val={this.state.applyEndTime}/>
            <Input title='申请人' placeholder='请填写申请人' change={(val)=>{this._onchange(val,'applyPerson')}}/>

            <Input title='联系方式' placeholder='请填写联系方式' change={(val)=>{this._onchange(val,'applyPhone')}}/>
            <Select title='申请原因' subTitle={this.state.applyFor}  press={()=>{this._onSelect('applyFor')}}/>

            <View style={styles.textAreaView}>
              <Text style={{fontSize:14,paddingTop:10,paddingBottom:10}}>申请内容</Text>
              
              
              <TextInput 
                ref={(ref) => this.contentInput = ref}
                  placeholder='请填写申请内容1234'
                  style={{fontSize:14,height:100,padding:0,paddingTop:5}}
                  textAlignVertical='top'
                  underlineColorAndroid="transparent"
                  multiline={true}
                  onChangeText={(val)=>{this._applyContent(val)}}
                  placeholderTextColor='#A9A9A9'
                  onFocus={()=>{this._onFocus()}}
                />
              
            </View>
            
          </View>
        </ScrollView>
        
        <TouchableOpacity  style={styles.btn} activeOpacity={0.6} onPress={()=>{this._submit()}}>
          <Text style={{color:'white',fontSize:16}}>提交</Text>
        </TouchableOpacity>
        <Toast ref="toast" position='bottom' positionValue={200} />
      </View>
    )
  }
}
class Input extends Component{
  render(){
    //<KeyboardAvoidingView  behavior="padding" enabled>
    return(
      
        <View style={[styles.inputRow,this.props.style]}>
          <Text style={{fontSize:14}}>{this.props.title}</Text>
          <TextInput 
              placeholder={this.props.placeholder}
              style={styles.searchInput}
              underlineColorAndroid="transparent"
              onChangeText={this.props.change}
              value={this.props.val}
              placeholderTextColor='#A9A9A9'
              placeholderTextFont={14}
            />
        </View>

    )
  }
}
class Select extends Component {
  render(){
    return(
      <View style={[styles.row,this.props.style]}>
        <Text style={styles.flex1}>{this.props.title}</Text>
        <TouchableOpacity style={styles.flex1} activeOpacity={0.5} onPress={this.props.press}>
          <Text style={styles.rightText}>{this.props.subTitle}</Text>
        </TouchableOpacity>
        {this.props.rightImg?
          <Image style={styles.imgStyle} source={require('../../images/arrow.png')}/>
        :
          <View style={styles.imgStyle}></View>
        }
      </View>
    )
  }
}
const styles = StyleSheet.create({
  btn:{
    //height:50,
    position:'absolute',
    bottom:isIphoneX()?40:20,
    left:20,
    right:20,
    backgroundColor:'#5fbcf9',
    padding:10,
    justifyContent:'center',
    alignItems:'center',
    borderRadius:5,
  },
  textAreaView:{
    marginLeft:20,
    marginRight:20,
  },
  inputRow:{
    flexDirection:'row',
    alignItems:'center',
    marginLeft:20,
    marginRight:10,
    borderBottomColor:'#ccc',
    borderBottomWidth:StyleSheet.hairlineWidth,
  },
  searchInput:{
    textAlign:'right',
    marginLeft:10,
    marginRight:14,
    padding:0,
    flex:1,
    height: 36, 
    color:'#A9A9A9',
  },
  imgStyle:{
    width:9,
    height:15,
    marginLeft:5,
  },
  rightText:{
    color:'#A9A9A9',
    fontSize:14,
    textAlign:'right',
    fontWeight:'100',
  },
  flex1:{
    flex:1,
    //borderWidth:1,
    //borderColor:'red',
    fontSize:14,
  },
  row:{
    flexDirection:'row',
    alignItems:'center',
    marginLeft:20,
    marginRight:10,
    paddingTop:10,
    paddingBottom:10,
    borderBottomColor:'#ccc',
    borderBottomWidth:StyleSheet.hairlineWidth,
  },
  container:{
    // position:'absolute',
    // top:0,
    // left:0,
    // right:0,
    // bottom:0,
    flex:1,
    height:'100%',
    backgroundColor:'#f0f0f0',

  }
})